package com.shouer.doc.ui.neworder.presenter;

import android.util.Log;
import android.widget.Toast;

import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.event.NewOrderEvent;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.neworder.model.HealthRecord;
import com.shouer.doc.ui.neworder.model.ReceiveHealthRecordResponse;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;
import com.shouer.doc.ui.neworder.response.QueryHealthOrderResponse;
import com.shouer.doc.ui.neworder.response.QueryNewOrderResponse;
import com.shouer.doc.ui.neworder.response.ReceiveOrderResponse;
import com.shouer.doc.ui.neworder.response.RefuseOrderResponse;
import com.shouer.doc.ui.neworder.view.INewOrdView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZXL on 2016/11/25.
 */

public class NewOrderListPresenterCompl implements INewOrderPresenter {


    private INewOrdView mNewOrdView;

    private int currentPageNo = 1;
    private int maxPageNo = 20;
    private int pageNum = 10;

    private boolean isRefreshing = false;
    private boolean isLoadingMore = false;

    private boolean isHealthRefreshing=false;
    private boolean isHealthLoadingMore=false;
    private int currentHealthPageNo = 1;
    private int maxHealthPageNo = 20;
    private int healthPageNum = 10;


    public NewOrderListPresenterCompl(INewOrdView mNewOrdView) {
        this.mNewOrdView = mNewOrdView;
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        mNewOrdView = null;
    }

    @Override
    public void receiveOrder(final SimpleOrderModel orderModel) {

        Log.d(NewOrderListPresenterCompl.class.getSimpleName(), "receiveOrder");
        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderModel.getOrderId());
        param.put("patId", orderModel.getPatId());
        param.put("docId", mNewOrdView.getUser().getUserId());
        param.put("type", "1");

        final GsonRequest<ReceiveOrderResponse> request = new GsonRequest("receiveOrder", ReceiveOrderResponse.class, new Response.Listener<ReceiveOrderResponse>() {
            @Override
            public void onResponse(ReceiveOrderResponse response) {

                response.setOrderModel(orderModel);
                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mNewOrdView.receiveOrderFailed("网络异常 接收失败");
            }
        });

        RequestUtil.sendRequest(mNewOrdView.getContext(), param, request);

    }

    @Override
    public void refuseOrder(final SimpleOrderModel orderModel) {

        Log.d(NewOrderListPresenterCompl.class.getSimpleName(), "receiveOrder");
        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderModel.getOrderId());
        param.put("patId", orderModel.getPatId());
        param.put("docId", mNewOrdView.getUser().getUserId());
        param.put("type", "0");

        final GsonRequest<RefuseOrderResponse> request = new GsonRequest("receiveOrder", RefuseOrderResponse.class, new Response.Listener<RefuseOrderResponse>() {
            @Override
            public void onResponse(RefuseOrderResponse response) {

                response.setOrderModel(orderModel);
                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mNewOrdView.refuseOrderFailed("网络异常 拒绝订单失败");
            }
        });

        RequestUtil.sendRequest(mNewOrdView.getContext(), param, request);


    }

    @Override
    public void queryNewOrd(int pageNo, int pageNum) {

        Map<String, String> param = new HashMap<>();
        param.put("pageNo", String.valueOf(pageNo));
        param.put("pageNum", String.valueOf(pageNum));
        param.put("docId", mNewOrdView.getUser().getUserId());
        param.put("orderState", String.valueOf(ShouerConst.ORDER_STATE_DOCTOR));

        if (pageNo == 1) {
            isRefreshing = true;
        } else {
            isLoadingMore = true;
        }

        final GsonRequest<QueryNewOrderResponse> request = new GsonRequest("queryOrder", QueryNewOrderResponse.class, new Response.Listener<QueryNewOrderResponse>() {
            @Override
            public void onResponse(QueryNewOrderResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isRefreshing = false;
                isLoadingMore = false;
                if (error instanceof ParseError) {
                    mNewOrdView.loadOrdDataFailed("返回数据格式错误 查询新订单失败");
                } else {
                    mNewOrdView.loadOrdDataFailed("网络异常 查询新订单失败");
                }

            }
        });

        RequestUtil.sendRequest(mNewOrdView.getContext(), param, request);

    }

    @Override
    public void queryNewHealthRecord(int pageNo, int pageNum)
    {
        Map<String, String> param = new HashMap<>();
        param.put("pageNo", String.valueOf(pageNo));
        param.put("pageNum", String.valueOf(pageNum));
        param.put("docId", mNewOrdView.getUser().getUserId());
        param.put("state","2");

        if (pageNo == 1) {
            isHealthRefreshing = true;
        } else {
            isHealthLoadingMore = true;
        }

        final GsonRequest<QueryHealthOrderResponse> request = new GsonRequest("queryHealthRecord", QueryHealthOrderResponse.class, new Response.Listener<QueryHealthOrderResponse>() {
            @Override
            public void onResponse(QueryHealthOrderResponse response) {

                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                isHealthRefreshing = false;
                isHealthLoadingMore = false;
                if (error instanceof ParseError) {
                    mNewOrdView.loadHealthOrdDataFailed("返回数据格式错误 查询新订单失败");
                } else {
                    mNewOrdView.loadHealthOrdDataFailed("网络异常 查询新订单失败");
                }

            }
        });

        RequestUtil.sendRequest(mNewOrdView.getContext(), param, request);
    }

    @Override
    public void receiveHealthRecord(final HealthRecord record)
    {
        Log.d(NewOrderListPresenterCompl.class.getSimpleName(), "receiveHealthRecord");
        Map<String, String> param = new HashMap<>();
        param.put("recId", record.getRecid());
        param.put("docId", mNewOrdView.getUser().getUserId());
        param.put("type", "3");

        final GsonRequest<ReceiveHealthRecordResponse> request = new GsonRequest("receiveHealthRecord", ReceiveHealthRecordResponse.class, new Response.Listener<ReceiveHealthRecordResponse>() {
            @Override
            public void onResponse(ReceiveHealthRecordResponse response) {

                response.setHealthRecord(record);
                EventBus.getDefault().post(response);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mNewOrdView.receiveOrderFailed("网络异常 接收失败");
            }
        });

        RequestUtil.sendRequest(mNewOrdView.getContext(), param, request);

    }

    /**
     * 查询新订单接口返回
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryNewOrderResponse response) {
        isRefreshing = false;
        isLoadingMore = false;
        if (response.getErrorCode() >= 0) {
            if (response.getPageNo() == 1) {
                currentPageNo = 1;
                mNewOrdView.refreshOrderList(response.getOrderInfoList());
            } else {
                if (null != response.getOrderInfoList() && response.getOrderInfoList().size() > 0) {
                    currentPageNo++;
                }
                mNewOrdView.attachOrdList(response.getOrderInfoList());
            }
        } else {
            mNewOrdView.loadOrdDataFailed(response.getErrorMsg());
            Toast.makeText(mNewOrdView.getContext(), response.getErrorMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 查询健康档案新订单接口返回
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryHealthOrderResponse response) {

        isHealthRefreshing=false;
        isHealthLoadingMore=false;
        if (response.getErrorCode()>=0)
        {
            if (response.getPageNo() == 1) {
                currentHealthPageNo = 1;
                mNewOrdView.refreshHealthOrderList(response);
            } else {
                if (null != response.getRecordList() && response.getRecordList().size() > 0) {
                    currentHealthPageNo++;
                }
                mNewOrdView.attachHealthOrdList(response);
            }
        }else
        {
            mNewOrdView.loadHealthOrdDataFailed(response.getErrorMsg());
        }

    }


    /**
     * 接受咨询订单接口返回
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ReceiveOrderResponse response) {
        if (response.getErrorCode() >= 0) {
            mNewOrdView.receiveOrderSuccess(response.getOrderModel());
        } else if (response.getErrorCode() == -3000) {
            mNewOrdView.orderHasBeReceived(response.getOrderModel(), response.getErrorMsg());
        } else {
            mNewOrdView.receiveOrderFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ReceiveHealthRecordResponse response)
    {
        if (response.getErrorCode() >= 0) {
            mNewOrdView.receiveHealthRecordSuccess(response.getHealthRecord());
        } else if (response.getErrorCode() == -3000) {
            mNewOrdView.healthRecordHasBeReceived(response.getHealthRecord(), response.getErrorMsg());
        } else {
            mNewOrdView.receiveHealthRecordFailed(response.getErrorMsg());
        }
    }

    /**
     * 拒绝咨询订单接口返回
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefuseOrderResponse response) {
        if (response.getErrorCode() >= 0) {
            mNewOrdView.refuseOrderSuccess(response.getOrderModel());
        } else {
            mNewOrdView.refuseOrderFailed(response.getErrorMsg());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NewOrderEvent event) {
        //refresh();
    }

    @Override
    public boolean refresh() {
            return refresh(false);
    }

    /**
     * 刷新咨询订单
     * */
    @Override
    public boolean refresh(boolean fause) {
        if (fause) {
            if (mNewOrdView.getApp().isUserLogin()) {

                queryNewOrd(1, pageNum);
                return true;

            } else {
                return false;
            }

        }

        if (isRefreshing || isLoadingMore || !mNewOrdView.getApp().isUserLogin()) {
            return false;
        }
        queryNewOrd(1, pageNum);
        return true;
    }

    /**
     * 查询更多咨询订单
     * */
    @Override
    public boolean loadMore() {
        if (isRefreshing || isLoadingMore || (currentPageNo + 1) > maxPageNo || !mNewOrdView.getApp().isUserLogin()) {
            return false;
        }
        queryNewOrd(currentPageNo + 1, pageNum);
        return true;
    }

    @Override
    public boolean refreshHealthRecord() {
        return refreshHealthRecord(false);
    }

    @Override
    public boolean refreshHealthRecord(boolean fause) {
        if (fause) {
            if (mNewOrdView.getApp().isUserLogin()) {

                queryNewHealthRecord(1, healthPageNum);
                return true;

            } else {
                return false;
            }

        }

        if (isHealthRefreshing || isHealthLoadingMore || !mNewOrdView.getApp().isUserLogin()) {
            return false;
        }
        queryNewHealthRecord(1, healthPageNum);
        return true;
    }

    @Override
    public boolean loadMoreHealthRecord() {
        if (isHealthRefreshing || isHealthLoadingMore || (currentHealthPageNo + 1) > maxHealthPageNo || !mNewOrdView.getApp().isUserLogin()) {
            return false;
        }
        queryNewHealthRecord(currentHealthPageNo + 1, healthPageNum);
        return true;
    }
}
